import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeIndex.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginIndex.vue'),
    meta: { redirectAlredyLogin: true }
  },
  {
    path: '/column/:id',
    name: 'column',
    component: () => import('../views/ColumnDetail.vue')
    // meta: { requiredLogin: true }
  },
  {
    path: '/create',
    name: 'create',
    component: () => import('../components/CreatePost.vue'),
    meta: { requiredLogin: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// to: 要进入的目标
// from: 要离开的目标
// next(): 如果有 next() 方法跳转 指向下一个路由
// router.beforeEach((to, from, next) => {
//   if (to.name !== 'login' && !store.state.user.isLogin) {
//     next({ name: 'login' })
//   } else {
//     next()
//   }
// })

// 通过路由原信息
router.beforeEach((to, from, next) => {
  console.log(to.meta)
  if (to.meta.requiredLogin && !store.state.user.isLogin) {
    next({ name: 'login' })
  } else if (to.meta.redirectAlredyLogin && store.state.user.isLogin) {
    next('/')
  } else {
    next()
  }
})

export default router
